package com.reebake.ideal.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.reebake.ideal.holder.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * 通用字段数据注入
 */
@Configuration
public class DataCommonFieldConfig {
	
    /**
     * 配置自动填充
     *
     */
    @Bean
    MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                // 数据类型要与fileName一致
                this.strictInsertFill(metaObject, "createdTime", Date.class, new Date());
                this.strictInsertFill(metaObject, "createdBy", String.class, findUserId());
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                // 数据类型要与fileName一致
                this.strictUpdateFill(metaObject, "updatedTime", Date.class, new Date());
                this.strictUpdateFill(metaObject, "updatedBy", String.class, findUserId());
            }
        };
    }

    private String findUserId() {
        return UserContextHolder.getCurrentUserId();
    }
}
